package top.lywivan.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;
import top.lywivan.netty.pojo.UserInfo;
import top.lywivan.netty.util.ProtostuffUtil;

import java.util.List;

/**
 * @author :lyw.ivan
 * @date :Created in 2022/8/14
 * @description : 基于ProtoStuff实现编码，此处将UserInfo序列化，真实开发中应该确定传输的Result类型
 * @version: 1.0
 */
@Slf4j
public class ProtoStuffEncoder extends MessageToMessageEncoder<UserInfo> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, UserInfo userInfo, List<Object> list) throws Exception {
        try {
            //将UserInfo进行序列化
            byte[] bytes = ProtostuffUtil.serialize(userInfo);
            //封装为ByteBuf对象
            ByteBuf buffer = channelHandlerContext.alloc().buffer(bytes.length);
            buffer.writeBytes(bytes);
            list.add(buffer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
